#include "CTimerManager.h"
#include "CTimer.h"

BEGIN_WARECOMMON

CTimerManager::~CTimerManager()
{

}

uint32 CTimerManager::SetTimer( uint32 uFrequency, TIMERFUNC pTimerCallback, void* pCallbackContext )
{
	m_uTimerIDSeed++;
	SWareTimer* pTimer = m_ObjList.CreateObject();
	pTimer->nCountdown = static_cast<int32>( uFrequency );
	pTimer->uFrequency = uFrequency;
	pTimer->pCallbackTimer = pTimerCallback;
	pTimer->pCallbackUserContext = pCallbackContext;
	pTimer->uRunTime = GetProcessTime();
	pTimer->uID = m_uTimerIDSeed;

	pTimer->pNext = m_pTimerRoot;
	m_pTimerRoot = pTimer;

	return m_uTimerIDSeed;
}

void CTimerManager::KillTimer( uint32 uTimerID )
{
	SWareTimer* pCurTimer = m_pTimerRoot;
	SWareTimer* pPrevTimer = NULL;
	while( pCurTimer != NULL )
	{
		if( pCurTimer->uID == uTimerID )
		{
			pCurTimer->nCountdown = 0;
			if( pPrevTimer )
			{
				pPrevTimer->pNext = pCurTimer->pNext;
			}
			else
			{
				m_pTimerRoot = pCurTimer->pNext;
			}

			m_ObjList.ReleaseObject( pCurTimer );
			break;
		}

		pPrevTimer = pCurTimer;
		pCurTimer = pCurTimer->pNext;
	}
}

void CTimerManager::Update()
{
	uint32 uCurTime = GetProcessTime();
	uint32 uElapseTime = 0;

	SWareTimer* pTimer = m_pTimerRoot;
	while( pTimer != NULL )
	{
		uElapseTime = uCurTime - pTimer->uRunTime;
		pTimer->nCountdown -= uElapseTime;
		if( pTimer->nCountdown <= 0 )
		{
			pTimer->pCallbackTimer( pTimer->uID, pTimer->pCallbackUserContext );
			pTimer->nCountdown = pTimer->uFrequency;
		}

		pTimer->uRunTime = uCurTime;
		pTimer = pTimer->pNext;
	}
}

END_WARECOMMON